#!/bin/bash

### BEGIN INIT INFO
# Provides: media-berry-server
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start Media Berry Server at boot time
# Description: Start Media Berry Server at boot time
### END INIT INFO

mediaBerryServerHome="/opt/media-berry/server"
pidFile="$mediaBerryServerHome/server.pid"

function running() {
	if [ -f "$pidFile" ]
        then
		pid=$(cat "$pidFile")
		output=$(ps aux | grep -v grep | grep "$pid")

		if [ "$output" != "" ]
		then
			return 0
		else
			return 1
		fi
	else
		return 1
	fi
}

function start() {
	if running
	then
        	echo "media-berry-server is already running"
        else
        	echo "Starting media-berry-server ..."
                /usr/bin/python "$mediaBerryServerHome/server.py" & echo $! > "$pidFile"
	fi
}

function stop() {
	if running
        then
        	echo "Stopping media-berry-server ..."

                pid=$(cat "$pidFile")

                kill "$pid"

                if running
                then
	                kill -9 "$pid"
                fi

                rm "$pidFile"
	else
		echo "media-berry-server is not running"
	fi
}

case "$1" in
	start)
		start
	;;
	stop)
		stop
	;;
	restart)
		stop
		start
	;;
	status)
		if running
		then
			echo "media-berry-server is started"
		else
			echo "media-berry-server is stopped"
		fi
	;;
	*)
		echo "Usage: $0 (start|stop|restart|status)"
	;;
esac
